import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, BadRequestException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class HttpExceptionFilter<T> implements ExceptionFilter {

  catch(exception: T, host: ArgumentsHost) {
    console.log("🚀 ~ 异常过滤器", exception)
    /**
     * 这里获取的 response和request 都是基于express平台下的
     */
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    
    const error:any = exception instanceof HttpException
    ? (exception as HttpException).getResponse()
    : exception.toString();
    console.log("HttpExceptionFilter<T> -> error", error)
    const status = exception instanceof HttpException 
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;
    const errorResponse = {
      message: error?.response?.message|| error.message || error || '请求失败',
      code: status,
      url: request.originalUrl // 错误的url地址
    }
    
    
    response.status(status==400?200:status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
 